<?php
namespace Home\Controller;
use Think\Model;
use Think\Controller;
class GoodsController extends Controller {

    /**
     * @param int $id 商品分类id
     */
    public function index($id = 0,$is_search = false){
        //商品种类
        $category = M("Category")->order('sort asc,u_time desc,id asc')->select();
        $category = get_category($category,GOODS_PID);
        //没id找数组第一个元素
        $cur_cate_id = 0;
        if(!$id){
            if($category){
                $wh['category_id'] = $cur_cate_id = reset($category)['id'];
                $goods = M("Goods")->where($wh)->select();
            }
        }else{
            if($category){
                $wh['category_id'] = $cur_cate_id = $id;
                $goods = M("Goods")->where($wh)->select();
            }
        }

        $this->assign('cur_cate_id',$cur_cate_id);//当前分类id
        $this->assign('category',$category);//分类下拉框
        $this->assign('goods',$goods);//goods
        $this->display();
    }

    /**
     * 搜索
     */
    public function search()
    {
        $wh['title'] = array('like','%'.I("get.content") .'%');
        $s_goods = M('Goods')->where($wh)->select();
        $this->assign('goods',$s_goods);//goods
        $this->display('index');
    }

    /**
     * @param $id 商品ID
     */
    public function info($id = 0){
        $this->return_number();
        //查找商品的详情
        $one = M('Goods')
            ->alias('g')
            ->field('g.*,gi.content')
            ->join('__GOODS_INFO__ as gi on g.id = gi.goods_id','left')
            ->find($id);

        if(!$one){
            $this->error('参数错误');
        }

        //该分类商品列表
        $wh['category_id'] =  $one['category_id'];
        $goods_list = M('Goods')->field('id,title')->where($wh)->select();


        foreach ($goods_list as $k => $v){
            $goods_list[$k]['title'] = subtext(strip_tags($v['title']),10,'...');
        }

        if($one){
            $one['title'] = subtext(strip_tags($one['title']),30,'...');
        }

        $wh1['id']=array('neq',$id);
        $hot_list =  M('Goods')->where($wh1)->order("rand()")->limit(0,4)->select();


        $this->assign('goods_list',$goods_list);
        $this->assign('hot_list',$hot_list);
        $this->assign('one',$one);//该商品详情
        $this->display();
    }

    public function addCart($number='',$color='',$attr='',$id='',$submit_type=0){
        $goods = M('Goods')->field('market_price,shop_price')->find($id);

//        var_dump($number,$color,$attr,$id,$submit_type);

        if(!$number || !$color || !$attr || !$id || !$goods){
            $this->error('参数错误');
        }
//        var_dump($submit_type);
//        exit;
//        是否登录
        if(!session('home_uid')){
            $url = urlencode('http://'.I('server.HTTP_HOST').U('',array('number'=>$number,'color'=>$color,'attr'=>$attr,'id'=>$id,'submit_type'=>$submit_type)));
            $this->error('请先登录',U('Login/index',array('return_url'=>$url)));
        }else{
            // 加入购物车
            $data['num'] = $number;
            $wh['color'] = $data['color'] = $color;
            $wh['attr'] = $data['attr'] = $attr;
            $wh['goods_id'] = $data['goods_id'] = $id;//这3个wh 确定是什么商品

            //设置user_id
            $wh['user_id'] = $data['user_id'] = session('home_uid');//确定是谁的数据

            $wh['status'] = $data['status'] = 0;//订单状态为0 说明是购物车数据


            // 查询数据库 有没有该商品的订单消息

            $one = M('Order')->field('id,num')->where($wh)->find();

            $data['market_price'] = $goods['market_price'];
            $data['shop_price'] = $goods['shop_price'];
            if($one){// 有：累加购买数量
                $data['id']  = $one['id'];
                $data['num'] += $one['num'];
                $data['u_time']  = time();
                $res = M("Order")->data($data)->save();

                if($res !== false){
                    if($submit_type == 1) {
                        //直接结算
                        // $url = U('User/checkout',array('id'=>$data['id'],'number'=>$number));
                        //重定向到New模块的Category操作
                        $this->redirect('User/checkout',array('id'=>$data['id'],'number'=>$number));
                    }else{
                        $this->success('加入购物车成功',U('User/cart'));
                    }
                }else{
                    $this->error('加入购物车失败');

                }

            }else{// 无：新增购物车

                $data['c_time']  = $data['u_time'] = time();
                $res = M('Order')->data($data)->add();
                if($res){
                    if($submit_type == 1){
                        $this->redirect('User/checkout',array('id'=>$res,'number'=>$number));
                    }else{
                        $this->success('加入购物车成功',U('User/cart'));
                    }
                }else{
                    $this->error('加入购物车失败');
                }
            }
        }
    }

    private function return_number()
    {
        $wh['o.u_time'] = array('lt',time() - 1800);
        $wh['status'] = 2;
        $wh['pay_type'] = 1;
        $order = M('Order')
            ->alias('o')
            ->field('o.id,o.goods_id,o.attr,o.color,o.num,o.status,o.u_time,g.title,g.shop_price as goods_shop_price,g.attr as goods_attr')
            ->where($wh)
            ->join('__GOODS__ as g on g.id = o.goods_id','left')
            ->select();
        // var_dump($order);exit;
        if($order){
            $model = new Model();
            $model->startTrans();//开启事务
            $data['status'] = 1;
            $data['u_time'] = time();
            foreach ($order as $k => $v) {
                //查看满不满足库存
                $goods_attr = json_decode($v['goods_attr'],true);//把属性转数组
                $number = $goods_attr[$v['attr']];//真正商品库存

                //商品表 统计要减的库存
                $goods[$v['goods_id']]['attr'][$v['attr']] = $v['num'];
                $goods[$v['goods_id']]['all_attr'] = $goods_attr;


                $data['id'] = $v['id'];
                $res = $model->table('__ORDER__')->data($data)->save();
                if($res === false){
                    $model->rollback();//有报错 回滚 操作 不更新订单信息
                    // $this->error('网络错误，请稍后在试');
                }
            }
            // var_dump($goods);
            // var_dump($data);
            // $model->rollback();
            // exit;
            // var_dump($goods);

            foreach ($goods as $kk => $vv) {
                $g['id'] = $kk;
                $nn = 0;
                foreach ($vv['attr'] as $kkk => $vvv) {
                    $nn += $vvv;
                    $vv['all_attr'][$kkk] += $vvv;
                }
                // var_dump($vv);
                // array('exp','score+1');// 用户的积分加1
                $g['number'] = array('exp','number+'.$nn);// 减库存
                $g['attr'] = json_encode($vv['all_attr']);
                $res = $model->table('__GOODS__')->data($g)->save();
                if($res === false){
                    $model->rollback();//有报错 回滚 操作 不更新库存
                    // $this->error('网络错误，请稍后在试');
                }
            }

            $model->commit();//都成功提交数据库
        }
    }
}